/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dibujar;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ByteLookupTable;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.PixelGrabber;
import java.awt.image.RescaleOp;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import ejemplo.Weight;
import ejemplo.neuralNetworkbak;
import ejemplo.utilidades;




/**
 *
 * @author samimikel
 */
public class pruebaImagen {

    private static BufferedImage image;
    private static Image loadedImage;
    private static int reconocidos = 0;
    
    
      /**
   * The down sample component used with this component.
   */
 // protected static Sample sample;

  /**
   * Specifies the left boundary of the cropping rectangle.
   */
  protected static int downSampleLeft;

  /**
   * Specifies the right boundary of the cropping rectangle.
   */
  protected static int downSampleRight;

  /**
   * Specifies the top boundary of the cropping rectangle.
   */
  protected static int downSampleTop;

  /**
   * Specifies the bottom boundary of the cropping rectangle.
   */
  protected static int downSampleBottom;

  /**
   * The downsample ratio for x.
   */
  public static double ratioX;

  /**
   * The downsample ratio for y
   */
  public static double ratioY;

  /**
   * The pixel map of what the user has drawn. Used to downsample it.
   */
  private static int[] pixelMap;






   static boolean isGreyscaleImage(PixelGrabber pg) {
    return pg.getPixels() instanceof byte[];
  }

   public static void filter(BufferedImageOp op) {
    BufferedImage filteredImage = new BufferedImage(image.getWidth(), image
        .getHeight(), image.getType());
    op.filter(image, filteredImage);
    image = filteredImage;
    
  }

  public static void convolve(float[] elements) {
    Kernel kernel = new Kernel(3, 3, elements);
    ConvolveOp op = new ConvolveOp(kernel);
    filter(op);
  }

  public static void negative() {
    byte negative[] = new byte[256];
    for (int i = 0; i < 256; i++)
      negative[i] = (byte) (255 - i);
    ByteLookupTable table = new ByteLookupTable(0, negative);
    LookupOp op = new LookupOp(table, null);
    filter(op);
  }

  public void sharpen() {
    float[] elements = { 0.0f, -1.0f, 0.0f, -1.0f, 5.f, -1.0f, 0.0f, -1.0f,
        0.0f };
    convolve(elements);
  }

   public static void brighten() {
    float a = 1.5f;
    float b = -20.0f;
    RescaleOp op = new RescaleOp(a, b, null);
    filter(op);
  }
   
   public static void blur() {
	    float weight = 1.0f / 9.0f;
	    float[] elements = new float[9];
	    for (int i = 0; i < 9; i++)
	      elements[i] = weight;
	    convolve(elements);
	  }
   
  public static void edgeDetect() {
    float[] elements = { 0.0f, -1.0f, 0.0f, -1.0f, 4.f, -1.0f, 0.0f, -1.0f,
        0.0f };
    convolve(elements);
  }

  public static BufferedImage toBufferedImage(Image image) {
        /** miramos uqe la imagen no sea ya una instancia de BufferedImage */
        if( image instanceof BufferedImage ) {
                /** genial, no hay que hacer nada */
                return( (BufferedImage)image );
        } else {
                /** nos aseguramos que la imagen está totalmente cargada */
                image = new ImageIcon(image).getImage();
                /** creamos la nueva imagen */
                BufferedImage bufferedImage = new BufferedImage(
                                                      image.getWidth(null),
                                                      image.getHeight(null),
                                                      BufferedImage.TYPE_USHORT_GRAY );
                Graphics g = bufferedImage.createGraphics();
                g.drawImage(image,0,0,null);
                g.dispose();
                return( bufferedImage );
        }
    }


          /*
        * calcula el factor de escala mínimo y en base a eso escala la imagen
        * según el dicho factor.
        * @param nMaxWidth minimo tamaño para el ancho
        * @param nMaxHeight minimo tamaño para el alto
        * @param imgSrc la imágen
        */
        public static BufferedImage scaleToSize(int nMaxWidth, int nMaxHeight, BufferedImage imgSrc) {
        int nHeight = imgSrc.getHeight();
        int nWidth = imgSrc.getWidth();
        double scaleX = (double)nMaxWidth / (double)nWidth;
        double scaleY = (double)nMaxHeight / (double)nHeight;
        double fScale = Math.min(scaleX, scaleY);
        return scale(fScale, imgSrc);
        }

        /*
        * escala una imagen en porcentaje.
        * @param scale ejemplo: scale=0.6 (escala la imágen al 60%)
        * @param srcImg una imagen BufferedImage
        * @return un BufferedImage escalado
        */
        public static BufferedImage scale(double scale, BufferedImage srcImg) {
        if (scale == 1 ) {
        return srcImg;
        }
        AffineTransformOp op = new AffineTransformOp
        (AffineTransform.getScaleInstance(scale, scale), null);

        return op.filter(srcImg, null);

        }

  protected static boolean hLineClear(int y)
  {
    int w = image.getWidth(null);
    for (int i = 0; i < w; i++)
    {
      System.out.println(image.getRGB(i, y));
     
      if (pixelMap[(y * w) + i] != -1)
        return false;
    }
    return true;
  }

  /**
   * This method is called to determine ....
   *
   * @param x
   *          The vertical line to scan.
   * @return True if there are any pixels in the specified vertical line.
   */
  protected static boolean vLineClear(int x)
  {
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    for (int i = 0; i < h; i++)
    {
    	 System.out.println(image.getRGB(i, x));
      if (pixelMap[(i * w) + x] != -1)
        return false;
    }
    return true;
  }

  /**
   * This method is called to automatically crop the image so that whitespace is
   * removed.
   *
   * @param w
   *          The width of the image.
   * @param h
   *          The height of the image
   */
  protected static void findBounds(int w, int h)
  {
    // top line
    for (int y = 0; y < h; y++)
    {
      if (!hLineClear(y))
      {
        downSampleTop = y;
        break;
      }

    }
    // bottom line
    for (int y = h - 1; y >= 0; y--)
    {
      if (!hLineClear(y))
      {
        downSampleBottom = y;
        break;
      }
    }
    // left line
    for (int x = 0; x < w; x++)
    {
      if (!vLineClear(x))
      {
        downSampleLeft = x;
        break;
      }
    }

    // right line
    for (int x = w - 1; x >= 0; x--)
    {
      if (!vLineClear(x))
      {
        downSampleRight = x;
        break;
      }
    }
  }

  /**
   * Called to downsample a quadrant of the image.
   *
   * @param x
   *          The x coordinate of the resulting downsample.
   * @param y
   *          The y coordinate of the resulting downsample.
   * @return Returns true if there were ANY pixels in the specified quadrant.
   */
  protected static boolean downSampleQuadrant(int x, int y)
  {
    int w = image.getWidth(null);
    int startX = (int) (downSampleLeft + (x * ratioX));
    int startY = (int) (downSampleTop + (y * ratioY));
    int endX = (int) (startX + ratioX);
    int endY = (int) (startY + ratioY);

    for (int yy = startY; yy <= endY; yy++)
    {
      for (int xx = startX; xx <= endX; xx++)
      {
        int loc = xx + (yy * w);

        if (pixelMap[loc] != -1)
          return true;
      }
    }

    return false;
  }
    public static String loadImage(String name) throws InterruptedException {

            JLabel label = new JLabel();
            MediaTracker media = new MediaTracker(label);

            loadedImage = Toolkit.getDefaultToolkit().getImage (name);
            media.addImage(loadedImage, 23);
            
            try
            {
               media.waitForID(23);
            }
            catch (InterruptedException e)
            {
               System.out.println ("Me han interrumpido");
               System.out.println ("Puede que la imagen todavía no haya terminado de cargarse");
            }
                    
           image= scaleToSize(20,20,toBufferedImage(loadedImage));
           utilidades.salvarImagen(image, "/jj.png","png");

              //loadedImage.getHeight(label);
        int w = image.getWidth(null);
        int h = image.getHeight(null);
        
        System.out.println("w="+w);
        System.out.println("h="+h);
        
        pixelMap = new int[w * h];

       image.getRGB(0, 0, w, h, pixelMap, 0, w);


      findBounds(w, h);

      ratioX = (double) (downSampleRight - downSampleLeft)
          / (double) 10;
      ratioY = (double) (downSampleBottom - downSampleTop)
          / (double) 10;

      String s="";
      for (int y = 0; y < 10; y++)
      {
        for (int x = 0; x <10; x++)
        {
          if (downSampleQuadrant(x, y)) {
              s=s+"1;";
           }

          else {
             s=s+"0;";
          }

        }
           s=s+"\n";
      }


      return (s);
     
  }

    public static void main(String [ ] args) throws InterruptedException, FileNotFoundException, IOException{

       String s=loadImage("/cara0.png");

        System.out.println(s);
       
//    	neuralNetwork nn = new neuralNetwork(100, 60, 6, utilidades.cargaFicheroPatrones("patronesCaras.txt"));
//    	
//		reconocidos = 0;
//		
//		nn.setCoficienteAprendizaje((float) 0.1);
//		utilidades.resetTime();
//		//Weight.loadWeight("PESOSCARAS.TXT");
//		
//		double porcentaje = 0.00;
//		
//		while (!nn.isfinishedLearning()) {
//
//			nn.entrenaRed();
//
//			porcentaje = (reconocidos * 100) / nn.getNumeroPatrones();
//
//			System.out.println(nn.getErrorGlobal());
//			System.out.println("reconocidos =" + String.valueOf(porcentaje)
//					+ "% /" + String.valueOf(reconocidos) + " de "
//					+ String.valueOf(nn.getNumeroPatrones()));
//			System.out.println("tiempo transcurrido ="
//					+ String.valueOf(utilidades.getHoraTranscurrido()) + ":"
//					+ String.valueOf(utilidades.getMinutoTranscurrido()) + ":"
//					+ String.valueOf(utilidades.getSegundoTranscurrido()));
//
//		}
//
//		System.out.println(" SE ACABO!!! iteraciones = "
//				+ String.valueOf(nn.getIteraciones()));
//
//		Weight.saveWeights("PESOSCARAS.TXT");
//
// 
  }
}
